package com.simtop.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.simtop.common.ServerResponse;
import com.simtop.pojo.User;
import com.simtop.pojo.experiment.Experiment;
import com.simtop.pojo.experiment.ExperimentVo;
import com.simtop.service.ExperimentService;
import com.simtop.util.Convert;
import com.simtop.util.ExcelUtils;
import com.simtop.util.FileUploadAndDownload;
import com.simtop.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.server.PathParam;
import java.util.ArrayList;
import java.util.List;


/**
 * @author lvoyngwei
 */
@RestController
@CrossOrigin
@RequestMapping("/experiment")
public class ExperimentController {

    @Autowired
    private ExcelUtils excelUtils;

    @Autowired
    private ExperimentService experimentService;

    @Autowired
    private FileUploadAndDownload fileUploadAndDownload;

    /**
     * 添加实验报告
     * @param experiment
     * @return
     */
    @PostMapping("/add")
    public ServerResponse addExperiment(Experiment experiment,
                                        @RequestParam("fabricPhotos") List<MultipartFile> fabricPhotos,
                                        @RequestParam("designPhotos") List<MultipartFile> designPhotos,
                                        @RequestParam("finishedPhotos") List<MultipartFile> finishedPhotos, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if(token == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        ArrayList<String> fabricPhoto = new ArrayList<>();
        ArrayList<String> designPhoto = new ArrayList<>();
        ArrayList<String> finishedPhoto = new ArrayList<>();
        try{
            if(fabricPhotos.size() != 0){
                for(MultipartFile file:fabricPhotos){
                    String upload = fileUploadAndDownload.upload(file);
                    fabricPhoto.add(upload);
                }
            }
            if(designPhotos.size() != 0){
                for(MultipartFile file:designPhotos){
                    String upload = fileUploadAndDownload.upload(file);
                    designPhoto.add(upload);
                }
            }
            if(finishedPhotos.size()!=0){
                for(MultipartFile file:finishedPhotos){
                    String upload = fileUploadAndDownload.upload(file);
                    finishedPhoto.add(upload);
                }
            }
            experiment.setUserId(u.getId());
            experiment.setDesignPhoto(JSONObject.toJSONString(designPhoto));
            experiment.setFabricPhoto(JSONObject.toJSONString(fabricPhoto));
            experiment.setFinishedPhoto(JSONObject.toJSONString(finishedPhoto));
            boolean a = experimentService.addExperiment(experiment);
            return ServerResponse.createBySuccessMsg("添加成功");
        }catch (Exception e){
            e.printStackTrace();
            return ServerResponse.createByErrorMsg("添加失败" + e.getMessage().toString());
        }
    }

    /**
     * 批改/修改 实验报告
     * @param experiment
     * @param request
     * @return
     */
    @PostMapping("/update")
    public ServerResponse updateExperiment(@RequestBody Experiment experiment,HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if(token == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        try{
            boolean a = experimentService.updateExperiment(experiment);
            return ServerResponse.createBySuccessMsg("实验批改成功");
        }catch (Exception e){
            e.printStackTrace();
            return ServerResponse.createByErrorMsg("实验批改失败");
        }
    }

    /**
     * 查询内容
     * @param experimentVo
     * @param request
     * @return
     */
    @PostMapping("/get")
    public ServerResponse getExperiment(@RequestBody ExperimentVo experimentVo, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if(token == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        try{
            experimentVo.setRoleId(u.getRoleId());
            experimentVo.setUserId(u.getId());
            PageHelper.startPage(experimentVo.getPageNum(),experimentVo.getPageSize());
            List<ExperimentVo> allExperiment = experimentService.getAllExperiment(experimentVo);
            PageInfo<ExperimentVo> pageInfo = new PageInfo<ExperimentVo>(allExperiment);
            return ServerResponse.createBySuccess("获取内容成功",pageInfo);
        }catch (Exception e){
            e.printStackTrace();
            return ServerResponse.createByErrorMsg("获取内容失败");
        }
    }

    /**
     * 删除 实验报告
     * @param data
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public ServerResponse deleteExperiment(@RequestBody String data,HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if(token == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        try{
            JSONObject parse = JSONObject.parseObject(data);
            Long[] ids = Convert.toLongArray(parse.getString("ids"));
            boolean a = experimentService.deleteExperiment(ids);
            return ServerResponse.createBySuccessMsg("实验删除成功");
        }catch (Exception e){
            return ServerResponse.createByErrorMsg("实验删除失败");
        }
    }


    /**
     * 导出
     * @param experimentVo
     * @return
     */
    @GetMapping("/export")
    public void export(ExperimentVo experimentVo,
                       @PathParam("classes")String classes,
                       @PathParam("userName")String userName,
                       @PathParam("token")String token,
                       HttpServletRequest request, HttpServletResponse response) {
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        experimentVo.setRoleId(u.getRoleId());
        experimentVo.setUserId(u.getId());
        experimentVo.setUserName(userName);
        experimentVo.setClasses(classes);
        List<ExperimentVo> allExperiment = experimentService.getAllExperiment(experimentVo);
        excelUtils.cooperationData(request,response,allExperiment,"实验报告内容",ExperimentVo.class);
    }
}
